#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#include <assert.h>
#include "threadpool.h"

threadpool_t* threadpool_create(int min_thr_num, int max_thr_num, int queue_max_size)
{
    int i;
    threadpool_t* pool = NULL;

    do{
        if( (pool = malloc(sizeof(threadpool_t))) == NULL){
            printf("malloc threadpool fail");
            break;
        }

        pool->min_thr_num = min_thr_num;
        pool->max_thr_num = max_thr_num;
        pool->busy_thr_num = 0;
        pool->live_thr_num = min_thr_num; /*活着的线程数 初值=最小线程数*/
        pool->queue_size = 0;
        pool->queue_max_size = queue_max_size;
        pool->queue_front = 0;
        pool->queue_rear = 0;
        pool->shutdown = false; /*不关闭线程池*/

        /*根据最大线程上限数, 给工作线程数组开辟空间, 并清零*/
        pool->threads = (pthread_t *)malloc(sizeof(pthread_t)*max_thr_num);
        if(pool->threads == NULL){
            printf("malloc threads fail");
            break;
        }
        memset(pool->threads, 0, sizeof(pthread_t)*max_thr_num);

        /*队列开辟空间*/
        pool->task_queue = (threadpool_task_t *)malloc(sizeof(threadpool_task_t)*queue_max_size);
        if(pool->task_queue == NULL){
            printf("malloc task_queue fail");
            break;
        }

        /*初始化互斥锁,条件变量*/
        if( 
            pthread_mutex_init(&(pool->lock), NULL) != 0 ||
            pthread_mutex_init(&(pool->thread_counter), NULL) != 0 ||
            pthread_cond_init(&(pool->queue_not_empty), NULL) != 0 ||
            pthread_cond_init(&(pool->queue_not_full), NULL) != 0
        
         ){
            printf("init the lock or cond fail ");
            break;
        }

        /*启动 min_thr_num 个 work thread*/
        for ( i = 0; i < min_thr_num; i++){
            pthread_create(&(pool->threads[i]), NULL, threadpool_thread, (void*)pool); 
        }
        pthread_create(&(pool->adjust_tid), NULL, adjust_thread, (void*) pool);

        return pool;
        
    } while (0); //在n多个代码中执行到某端代码出错不想继续执行下面代码 可以使用do{break;}while(0) 比goto __error好些  
    
    threadpool_free(pool); /*前面代码调用失败,释放pool存储空间*/

    return NULL;
}

int threadpool_free(threadpool_t* pool)
{
    if(pool == NULL){
        return -1;
    }
    if(pool->task_queue){
        free(pool->task_queue);
    }
    if(pool->threads){
        free(pool->threads);
        pthread_mutex_lock(&(pool->lock));
        pthread_mutex_destroy(&(pool->lock));
        pthread_mutex_lock(&(pool->thread_counter));
        pthread_mutex_destroy(&(pool->thread_counter));
        pthread_cond_destroy(&(pool->queue_not_empty));
        pthread_cond_destroy(&(pool->queue_not_full));
    }
    free(pool);
    pool = NULL;
    return 0;
}

/* 线程池中各个工作线程 */
void* threadpool_thread(void* threadpool)
{
    threadpool_t* pool = (threadpool_t *)threadpool;
    threadpool_task_t task;

    while (true){
        /* 刚创建出线程,等待任务队列里有任务,否则阻塞等待。任务队列有任务后再唤醒接收任务 */
        
        //只要操作这个线程池,就都需要上锁 锁住这个结构体
        pthread_mutex_lock(&(pool->lock));

        /*queue_size == 0 说明没有任务, 调用wait阻塞在条件变量上, 若有任务,跳过该while*/
        while ((pool->queue_size == 0) && (!pool->shutdown)){
            printf("thread 0x%x is waiting\n", (unsigned int)pthread_self());
            pthread_cond_wait(&(pool->queue_not_empty), &(pool->lock));

            /*清除指定数目的空闲线程,, 如果要结束的线程个数不大于0,结束线程*/
            if(pool->wait_exit_thr_num > 0){
                pool->wait_exit_thr_num--;

                /*如果线程池里线程个数大于最小值时可以结束当前线程*/
                if(pool->live_thr_num > pool->min_thr_num){
                    printf("thread 0x%x is exiting\n", (unsigned int)pthread_self());
                    pool->live_thr_num--;
                    pthread_mutex_unlock(&(pool->lock));
                    pthread_exit(NULL);
                }
            }
        }
        
        /*如果指定了true, 要关闭线程池里的每个线程, 自行退出处理*/
        if(pool->shutdown){
            pthread_mutex_unlock(&(pool->lock));
            printf("thread 0x%x is exiting\n", (unsigned int)pthread_self());
            pthread_exit(NULL);
        }

        /*从任务队列获取任务, 是一个出队的操作*/
        task.function = pool->task_queue[pool->queue_front].function;
        task.arg = pool->task_queue[pool->queue_front].arg;
        pool->queue_front = (pool->queue_front + 1) % pool->queue_max_size; /*出队模拟环形队列*/
        pool->queue_size--;

        /*通知可以有新的任务添加进来*/
        pthread_cond_broadcast(&(pool->queue_not_full));

        /*任务取出后,立即将线程池锁释放*/
        pthread_mutex_unlock(&(pool->lock));

        /*执行任务*/
        printf("thread 0x%x is start working\n", (unsigned int)pthread_self());
        pthread_mutex_lock(&(pool->thread_counter)); //给忙状态加锁
        pool->busy_thr_num++;//忙状态线程数+1
        pthread_mutex_unlock(&(pool->thread_counter));//给忙状态解锁
        (*(task.function))(task.arg); //执行回调函数任务

        /*任务结束处理*/
        printf("thread 0x%x is end working\n", (unsigned int)pthread_self());
        pthread_mutex_lock(&(pool->thread_counter));
        pool->busy_thr_num--; /*处理掉一个任务,忙的状态线程数-1*/
        pthread_mutex_unlock(&(pool->thread_counter));
    }
    pthread_exit(NULL);
    return (NULL);
}

/*管理线程*/
void* adjust_thread(void* threadpool)
{
    int i;
    threadpool_t* pool = (threadpool_t *)threadpool;   
    while (!pool->shutdown){
        sleep(DEFAULT_TIME); /*定时 对线程池管理*/

        pthread_mutex_lock(&(pool->lock));
        int queue_size = pool->queue_size;          /*关注 任务数*/
        int live_thr_num = pool->live_thr_num; /*存活 线程数*/
        pthread_mutex_unlock(&(pool->lock));

        pthread_mutex_lock(&(pool->thread_counter));
        int busy_thr_num = pool->busy_thr_num;
        pthread_mutex_unlock(&(pool->thread_counter));

        /*创建新线程 算法： 任务数量大于线程池MIN_WAIT_TASK_NUM线程个数, 且存活的线程数少于最大线程个数时 如: 30>10 && 40 <100*/
        if(queue_size >= MIN_WAIT_TASK_NUM && live_thr_num < pool->max_thr_num){
            pthread_mutex_lock(&(pool->lock));
            int add = 0;

            /*一次性增加 DEFAULT_THREAD 个线程*/
            for (i = 0; i < pool->max_thr_num && add < DEFAULT_THREAD_VARY 
                                    && pool->live_thr_num < pool->max_thr_num; i++){
                if(pool->threads[i] == 0 || !is_thread_alive(pool->threads[i])){
                    pthread_create(&(pool->threads[i]), NULL, threadpool_thread, (void*)pool);
                    add++;
                    pool->live_thr_num++;
                }
            }
        
            pthread_mutex_unlock(&(pool->lock));
        }

        /*销毁多余的空闲线程 算法:  忙线程x2 小于 存活的线程数 且 存活的线程数 大于最小线程数*/
        if( (busy_thr_num * 2) < live_thr_num && live_thr_num > pool->min_thr_num ){
            
            /*一次性销毁DEFAULT_THREAD个线程, 随机10个即可 */
            pthread_mutex_lock(&(pool->lock));
            pool->wait_exit_thr_num = DEFAULT_THREAD_VARY; /*销毁的线程数 设置为10 */
            pthread_mutex_unlock(&(pool->lock));

            for ( i = 0; i < DEFAULT_THREAD_VARY; i++){
                /*通知出在空闲状态的线程, 他们会自动终止*/
                pthread_cond_signal(&(pool->queue_not_empty));
            }
        }
    }
    
    pthread_exit(NULL);
    return (NULL);
}

int is_thread_alive(pthread_t tid)
{
    int kill_rc = pthread_kill(tid, 0);
    if(kill_rc == ESRCH){
        return 0;
    }
    return 1;
}

//把任务添加到队列中
int threadpool_add(threadpool_t* pool, void*(*function)(void* arg), void* arg)
{
    assert(pool != NULL);
    assert(function != NULL);
    assert(arg != NULL);

    pthread_mutex_lock(&(pool->lock));
    /*队列满时 等待*/
    while ( (pool->queue_size == pool->queue_max_size) && (!pool->shutdown) ){
        pthread_cond_wait(&(pool->queue_not_full), &(pool->lock));
    }
    
    if(pool->shutdown){
        pthread_mutex_unlock(&(pool->lock));
    }

    //添加任务到循环队列(内存还是线性结构,但是逻辑上是环形的)
    if(pool->task_queue[pool->queue_rear].arg != NULL){
        free(pool->task_queue[pool->queue_rear].arg);
        pool->task_queue[pool->queue_rear].arg = NULL;
    }
    pool->task_queue[pool->queue_rear].function = function;
    pool->task_queue[pool->queue_rear].arg = arg;
    pool->queue_rear = (pool->queue_rear + 1) % pool->queue_max_size;
    pool->queue_size++;

    //每次加完任务,发个信号给线程
    //若没有线程处于等待状态,此句无效,但不影响
    pthread_cond_signal(&(pool->queue_not_empty));
    pthread_mutex_unlock(&(pool->lock));
    return 0;
}

int threadpool_destroy(threadpool_t* pool)
{
    if(pool == NULL){
        return -1;
    }

    pool->shutdown = true;

    pthread_join(pool->adjust_tid, NULL);
    pthread_cond_broadcast(&(pool->queue_not_empty));
    for (int i = 0; i < pool->min_thr_num; i++){
        pthread_join(pool->threads[i], NULL);
    }
    threadpool_free(pool);
    return 0;
}